<?php
/*
 * 公共处理文件
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 7b5da40f1eead6af0cd8ea2b4196565a34c969c3 $
 */
defined('IN_IXDCW') or exit('Access Denied');
require DT_CORE . '/member/favorite.class.php';
require_once DT_INC . '/post.func.php';
switch ($action) {
	case 'captcha':
		if (strlen($aCaptcha) < 4) exit('1');
		Session::start();
		if (!isset($_SESSION['captchastr'])) exit('2');
		$aCaptcha = Str::convert($aCaptcha, 'UTF-8', DT_CHARSET);
		if ($_SESSION['captchastr'] != md5(md5(strtoupper($aCaptcha) . DT_KEY . $DT_IP))) exit('false');
		exit('true');
		break;
    case 'areapos':
        if (!$aId) {
            exit(json_encode(array('errNo'=>1, 'errMsg'=> '不正确的地区')));
        }
        $area = Area::get($aId);
        if (!isset($area['child']) || $area['child']) {
            exit(json_encode(array('errNo'=>2, 'errMsg' => '请选择详细的地区位置！','content'=>Area::pos($aId, ''))));
        }
        $area =  Area::pos($aId, '');
        exit(json_encode(array('errNo'=>0, 'content'=>$area)));
        break;
	case 'new':
		if ($_userid) {
			$r     = $db->getOne("SELECT message,chat FROM {$db->getPre()}member WHERE userid=$_userid");
			$chats = $db->getAll("SELECT * FROM {$db->getPre()}chat WHERE touser='$_username' or fromuser='$_username'");
			if ($chats) {
				$MOD = PCache::read('module-2.php');
				foreach ($chats as $chat) {
					$filename = DT_ROOT . '/file/chat/' . timetodate($chat['addtime'], 'Ym/dH') . '/' . $chat['chatid'] . '.php';
					if ($chat['status'] != 2 && $chat['status'] != 3) {
						$db->query("DELETE FROM {$db->getPre()}chat WHERE chatid='" . $chat['chatid'] . "'");
						File::del($filename);
					} else {
						if ($chat['status'] == 2 && $DT_TIME - $chat['addtime'] > 180) {
							$str     = File::get($filename);
							$str     = explode("\n", $str);
							$content = '';
							foreach ($str as $d) {
								list($time, $name, $word) = explode("|", $d);
								if ($time > $chat['addtime']) {
									$time = timetodate($time, 'H:i:s');
									if (preg_match_all("/\:([0-9]{3,})\)/i", $word, $m)) {
										foreach ($m[0] as $u) {
											$f = 'face/' . substr($u, 1, -1) . '.gif';
											if (is_file(DT_ROOT . '/' . $MOD['moduledir'] . '/' . $f)) $word = str_replace($u, '<img src="' . $f . '"/>', $word);
										}
									}
									if ($word) $content .= "$name" . "&nbsp;$time" . "<br/><p>$word</p>";
								}
							}
							$title = "会员{$chat['fromuser']}请求与您对话，您未接受对话，对话记录保存到您的站内信";
							if ($content) send_message($chat['touser'], $title, $content);
							$db->query("UPDATE {$db->getPre()}chat SET status=0 WHERE chatid='" . $chat['chatid'] . "'");
							$db->query("UPDATE {$db->getPre()}member SET chat=chat-1 WHERE username='" . $chat['touser'] . "'");
						}
					}
				}
			}
			if ($r) {
				echo sprintf('%s(%s);', $_GET['callback'], json_encode($r));
			} else {
				echo sprintf('%s(%s);', $_GET['callback'], json_encode(array(0, 0)));
			}
		} else {
			echo sprintf('%s(%s);', $_GET['callback'], json_encode(array(0, 0)));
		}
		break;
	case 'doctitle':
		isset($value) or $value == '';
		if (!Str::test("/[\x{4e00}-\x{9fa5}a-zA-Z]{6,}/ui", $value)) {
			echo 'false';
		}
		$arr = $db->getOne("select * from xd_merchant_doc where title='{$value}'");
		if ($arr) {
			echo 'false';
		} else {
			echo 'true';
		}
		break;
	case 'getDocidByTitle':
		isset($value) or $value == '';
		$did = $db->getVar("select did from xd_merchant_doc where title='{$value}'");
		if ($did) {
			echo $did;
		} else {
			echo 'false';
		}
		break;
	case 'area':
		$area_title    = Str::convert($area_title, 'UTF-8', DT_CHARSET);
		$area_extend   = isset($area_extend) ? stripslashes($area_extend) : '';
		$areaid        = isset($areaid) ? intval($areaid) : 0;
		$area_deep     = isset($area_deep) ? intval($area_deep) : 0;
		$area_id       = isset($area_id) ? intval($area_id) : 1;
		$area_moduleid = isset($area_moduleid) ? intval($area_moduleid) : '1';
		echo get_area_select($area_title, $areaid, $area_extend, $area_deep, $area_id, $area_moduleid);
		break;
	case 'areaCombo':
		$aPid      = intval($aPid);
		$aPostName = strval($aPostName);
		$aMid      = intval($aMid);
		exit(Post::areaCombo($aPostName, $aPid, '', true, $aMid));
		break;
	case 'cateCombo':
		$aPid      = intval($aPid);
		$aPostName = strval($aPostName);
		$aMid      = intval($aMid);
		$aDisabled = intval($aDisabled);
		exit(Post::cateCombo($aPostName, $aPid, $aMid, '', true, $aDisabled));
		break;
	case 'category':
		$category_title    = Str::convert($category_title, 'UTF-8', DT_CHARSET);
		$category_extend   = isset($category_extend) ? stripslashes($category_extend) : '';
		$category_moduleid = isset($category_moduleid) ? intval($category_moduleid) : 1;
		if (!$category_moduleid) exit;
		$category_deep = isset($category_deep) ? intval($category_deep) : 0;
		$cat_id        = isset($cat_id) ? intval($cat_id) : 1;
		$_child        = array();
		if ($_groupid == 1 && $_admin == 2) {
			$R = PCache::read('right-' . $_userid . '.php');
			if (isset($R[$category_moduleid]['index']['catid'])) {
				$_catids = $R[$category_moduleid]['index']['catid'];
				if ($_catids && is_array($_catids)) {
					$_childs = '';
					$result  = $db->query("SELECT arrchildid FROM {$db->getPre()}category WHERE catid IN (" . implode(',', $_catids) . ")");
					while ($r = $db->fetchArray($result)) {
						$_childs .= ',' . $r['arrchildid'];
					}
					if ($_childs) {
						$_childs = substr($_childs, 1);
						$_child  = explode(',', $_childs);
					}
				}
			}
		}
		echo get_category_select($category_title, $catid, $category_moduleid, $category_extend, $category_deep, $cat_id);
		break;
	case 'property':
		$CAT or exit;
		$CAT['property'] or exit;
		include DT_INC . '/property.func.php';
		$admin    = (isset($admin) && $admin) ? 1 : 0;
		$moduleid = $CAT['moduleid'];
		$options  = property_option($catid);
		$values   = $itemid ? property_value($moduleid, $itemid) : array();
		$select   = '<select id="property_required" style="display:none;">';
		$table    = '';
		foreach ($options as $k => $v) {
			isset($values[$v['oid']]) or $values[$v['oid']] = '';
			if ($v['required']) {
				$star = '<span class="f_red">*</span> ';
			} else {
				$star = $admin ? '<span class="f_hid">*</span> ' : '';
			}
			$table .= '<tr><td class="tl">' . $star . $v['name'] . '</td><td class="tr">' . property_html($values[$v['oid']], $v['oid'], $v['type'], $v['value'], $v['extend']) . ' <span class="f_red" id="dproduct-' . $v['oid'] . '"></span></td></tr>';
			$select .= $v['required'] ? '<option value="' . $v['oid'] . '">' . $v['name'] . '</option>' : '';
		}
		$select .= '</select>';
		echo $table . $select;
		break;
	case 'clear':
		@ignore_user_abort(true);
		Session::start();
		if ($_SESSION['uploads']) {
			foreach ($_SESSION['uploads'] as $file) {
				PictureUpload::deletePicture($file, $_userid);
			}
			$_SESSION['uploads'] = array();
		}
		break;
	case 'ipage':
		isset($job) or exit;
		if ($job == 'sell') {
			$moduleid = 5;
		} else if ($job == 'buy') {
			$moduleid = 6;
		} else {
			exit;
		}
		Template::tag("moduleid=$moduleid&condition=status=3&areaid=$city_id&pagesize=" . $DT['page_trade'] . "&page=$page&datetype=2&order=addtime desc&time=addtime&template=list-trade");
		break;
	case 'keyword':
		$mid = isset($mid) ? intval($mid) : 0;
		$mid or exit;
		isset($MODULE[$mid]) or exit;
		Template::tag("moduleid=$mid&table=keyword&condition=moduleid=$mid and status=3&pagesize=10&order=total_search desc&template=list-search_kw");
		break;
	case 'tipword':
		if (!$DT['search_tips']) exit;
		$mid = isset($mid) ? intval($mid) : 0;
		$mid or exit;
		isset($MODULE[$mid]) or exit;
		if (!$word || strlen($word) < 2 || strlen($word) > 30) exit;
		$word = Str::convert($word, 'UTF-8', DT_CHARSET);
		$word = str_replace(array(' ', '*', "\'"), array('%', '%', ''), $word);
		if (preg_match("/^[a-z0-9A-Z]+$/", $word)) {
			Template::tag("moduleid=$mid&table=keyword&condition=moduleid=$mid and letter like '%$word%'&pagesize=10&order=total_search desc&template=list-search_tip", -2);
		} else {
			Template::tag("moduleid=$mid&table=keyword&condition=moduleid=$mid and keyword like '%$word%'&pagesize=10&order=total_search desc&template=list-search_tip", -2);
		}
		break;
	case 'letter':
		preg_match("/[a-z]{1}/", $letter) or exit;
		$cols     = isset($cols) ? intval($cols) : 5;
		$precent  = ceil(100 / $cols);
		$CATEGORY = PCache::read('category-' . $moduleid . '.php');
		$CATALOG  = array();
		foreach ($CATEGORY as $k => $v) {
			if ($v['letter'] == $letter) $CATALOG[] = $v;
		}
		include template('letter', 'chip');
		break;
	case 'city':
		$lists  = array();
		$result = $db->query("SELECT areaid,name,style,domain,letter FROM {$db->getPre()}city ORDER BY letter,listorder");
		while ($r = $db->fetchArray($result)) {
			$r['linkurl']                      = $r['domain'] ? $r['domain'] : SITE_URL . 'api/' . rewrite('city.php?areaid=' . $r['areaid']);
			$lists[strtoupper($r['letter'])][] = $r;
		}
		include template('city', 'chip');
		break;
	case 'ckpath':
		if ($_groupid != 1) exit;
		if ($moduleid < 5) exit;
		if (strlen($path) < 5) exit;
		$path  = Str::convert($path, 'UTF-8', DT_CHARSET);
		$table = get_table($moduleid);
		if ($table) {
			$sql = "filepath='$path'";
			if ($itemid) $sql .= " AND itemid!=$itemid";
			if ($db->getOne("SELECT itemid FROM {$table} WHERE $sql")) {
				exit(lang('message->ajax_filepath_exists'));
			} else {
				exit(lang('message->ajax_filepath_not_exists'));
			}
		}
		break;
	case 'member':
		isset($job) or $job = '';
		require DT_CORE . '/member/common.inc.php';
		isset($value) or $value == '';
		$value = Str::convert($value, 'UTF-8', DT_CHARSET);
		require_once MD_ROOT . '/member.class.php';
		$do = new member;
		if (isset($userid) && $userid) $do->userid = $userid;
		switch ($job) {
			case 'username':
				//if (!$value) exit($L['member_username_match']);
				if ($do->username_exists($value)) {
					echo 'false';
				} else {
					echo 'true';
				};
				break;
			case 'passport':
				if (!$value) exit;
				if (!$do->is_passport($value)) exit($do->errmsg);
				break;
			case 'password':
				if (!$do->is_password($value, $value)) exit($do->errmsg);
				break;
			case 'payword':
				if (!$do->is_payword($value, $value)) exit($do->errmsg);
				break;
			case 'email':
				$value = trim($value);
				//if (!$do->is_email($value)) exit($do->errmsg);
				if ($do->email_exists($value)) {
					echo 'false';
				} else {
					echo 'true';
				}
				Session::start();
				$_SESSION['regemail'] = md5(md5($value . DT_KEY . $DT_IP));
				break;
			case 'emailcode':
				Session::start();
				$value = trim($value);
				if (!preg_match("/[0-9]{6}/", $value) || $_SESSION['email_code'] != md5($_SESSION['email'] . '|' . $value)) exit('&nbsp;');
				break;
			case 'company':
				if (!$value) exit($L['member_company_null']);
				if (!$do->is_company($value)) exit($L['member_company_reg']);
				if ($do->company_exists($value)) exit($L['member_company_reg']);
				break;
			case 'get_company':
				$user = $do->get_one($value);
				if ($user) {
					echo '<a href="' . $user['linkurl'] . '" target="_blank" class="t">' . $user['company'] . '</a>' . ($user['vip'] ? ' <img src="' . DT_SKIN . 'image/vip.gif" align="absmiddle"/> <img src="' . DT_SKIN . 'image/vip_' . $user['vip'] . '.gif" align="absmiddle"/>' : '');
				} else {
					echo '1';
				}
				exit;
				break;
		}
		break;
	case 'get_data':
		if (!$_userid) exit;
		$mid = isset($mid) ? intval($mid) : 0;
		$mid or exit;
		isset($MODULE[$mid]) or exit;
		$file    = DT_ROOT . '/file/user/' . dalloc($_userid) . '/' . $_userid . '/editor.data.' . $mid . '.php';
		$content = File::get($file);
		if ($content) {
			echo substr($content, 13);
		} else {
			echo '';
		}
		break;
	case 'save_data':
		if (!$_userid) exit;
		$mid = isset($mid) ? intval($mid) : 0;
		$mid or exit;
		isset($MODULE[$mid]) or exit;
		if (!$content) exit;
		$content = stripslashes($content);
		$content = Str::convert($content, 'UTF-8', DT_CHARSET);
		$content = '<?php exit;?>' . timetodate($DT_TIME) . $content;
		File::put(DT_ROOT . '/file/user/' . dalloc($_userid) . '/' . $_userid . '/editor.data.' . $mid . '.php', $content);
		break;
	case 'captcha':
		if (strlen($captcha) < 4) exit('1');
		Session::start();
		if (!isset($_SESSION['captchastr'])) exit('2');
		$captcha = Str::convert($captcha, 'UTF-8', DT_CHARSET);
		if ($_SESSION['captchastr'] != md5(md5(strtoupper($captcha) . DT_KEY . $DT_IP))) exit('3');
		exit('0');
		break;
	case 'question':
		if (strlen($answer) < 1) exit('1');
		$answer = stripslashes($answer);
		$answer = Str::convert($answer, 'UTF-8', DT_CHARSET);
		Session::start();
		if (!isset($_SESSION['answerstr'])) exit('2');
		if ($_SESSION['answerstr'] != md5(md5($answer . DT_KEY . $DT_IP))) exit('3');
		exit('0');
		break;
	// 咨询的调用
	case 'servicerSearch':
		// aid 地区id
		// mid 模块id
		$live = new Live();
		$mid = isset($mid) ? (int) $mid : 0;
		exit($live->servicerSearch($aid, $mid, LIVE::RETURN_TYPE_JSON));
		break;

	case 'kwSearch':
		$live = new Live();
		exit($live->kwSearch($kw));
		break;

	case 'answer';
		$live = new Live();
		exit($live->answer($aid));
		break;
	case 'addtofav':
		$moduleid  = intval($moduleid);
		$value     = intval($value);
		$ext_value = intval($ext_value);
		if (!$moduleid) {
			exit('请选择收藏的类型！');
		}
		if (!$value) {
			exit('请选择收藏的项目！');
		}
		if (!$_userid) {
			exit("请您先登陆！");
		}
		$info = array(
			'moduleid'  => $moduleid,
			'value'     => $value,
			'ext_value' => $ext_value,
		);
		$obj  = new Fav();
		$res  = $obj->add($info, $_userid);
		if ($res) {
			exit('收藏成功！');
		} else {
			exit("已经收藏过了，请不要重复操作！");
		}
		break;
	case 'unload':
		if ($act == 'add') {
			preg_match_all('/<img(.*)src=".*(file[^"]+)"[^>]+>/isU', Str::stripSlashes($kcon), $arr);
			foreach ($arr[2] as $v) {
				unlink(DT_ROOT . '/' . $v);
			}
		}
		if ($act == 'edit') {
			preg_match_all('/<img(.*)src=".*(file[^"]+)"[^>]+>/isU', Str::stripSlashes($content), $imgarr);
			preg_match_all('/<img(.*)src=".*(file[^"]+)"[^>]+>/isU', Str::stripSlashes($kcon), $arr);
			foreach (array_diff($arr[2], $imgarr[2]) as $v) {
				unlink(DT_ROOT . '/' . $v);
			}
		}
		break;
	case 'sysLetter':
		if (!$input) exit(json_encode(array('errNo' => 1, 'errMsg' => '不正确的输入!')));
		$length = isset($length) ? intval($length) : 1;
		exit(json_encode(array('errNo' => 0, 'letter' => Str::text2py($input, $length))));
		break;
	case 'wzchaxun':
		isset($provid) or $provid == '';
		$str          = $db->getAll("select a.areaname ,a.url from xd_area_chaxun as a ,xd_area as b  where b.parentid=$provid and a.areaid = b.areaid and a.url!=''");
		$strs['city'] = $str;
		if (empty($strs['city'])) {
			$strs['city'] = $db->getAll("select areaname,url from xd_area_chaxun where areaid = $provid and url!=''");
		}
		echo json_encode($strs);
		break;
	case 'checkcard':
		require DT_INC . '/module.func.php';
		$checkcardDb      = Db('owncard');
		$checkcarAction   = new OwnCardModule();
		$MOD              = PCache::read('module-37.php');
		$post['cardnum']  = str_replace(' ', '', $cardnum);
		$post['checknum'] = $checknum;
		$post['cardcode'] = strtolower($cardcode);
		//检查编号是否存在
		$getcode = $checkcardDb->getCodenum($post['cardnum']);
		if ($getcode) {
			//检查编号是否已被使用
			if (!$checkcardDb->checkNum($post['cardnum'])) {
				if ($getcode !== $post['cardcode']) {
					$checknum = $checkcarAction->subtract($checknum, $username);
					$alert    = '认证失败，密码错误！';
				} else {
					$post['username']   = $username;
					$post['addtime']    = $DT_TIME;
					$post['status']     = 1;
					$post['expiretime'] = strtotime($MOD['expiretime']);
					$checkcardDb->updateUsername($post);
					$alert = '恭喜您，认证成功！';
					cardmoney_add($username, 600);
					cardmoney_record($username, 600, 'system', '车主金卡认证通过', '车主金卡认证通过');
					send_message($username, "恭喜您成功激活讯都车主金卡", "恭喜您成功激活讯都车主金卡，600元专项资金已汇入您的
					<a href=" . url('member/cardmoney') . ">金卡专户</a>！");
					$success = 'true';
				}
			} else {
				$checknum = $checkcarAction->subtract($checknum, $username);
				$alert    = '认证失败,编号已被使用！';
			}
		} else {
			$checknum = $checkcarAction->subtract($checknum, $username);
			$alert    = '认证失败,编号不存在！';
		}
		$return = array('checknum' => $checknum, 'msg' => $alert, 'success' => $success);
		exit(json_encode($return));
		break;
	case 'getcity':

		$pid = isset($pid) ? intval($pid) : 0;
		$do  = new AdModule();
		if ($pid) {
			$do->setPid($pid);
			$p = $do->getOnePlace();
		}
		if ($p) {
			$placeResidueCity = $do->getPlaceResidueCity($pid);
		}

		$return = array();
		foreach ($placeResidueCity as $areaid) {
			if (in_array($areaid["areaid"], $provs) || in_array($AREA[$areaid["areaid"]]["parentid"], $provs)) {
				$return_temp['cityId']   = $areaid["areaid"];
				$return_temp['cityName'] = $areaid["name"];
				$return[]                = $return_temp;
			}
		}
		exit(json_encode($return));
		break;
	case 'getprice':

		$pid = isset($pid) ? intval($pid) : 0;
		$do  = new AdModule();
		if ($pid) {
			$do->setPid($pid);
			$p = $do->getOnePlace();
		}
		if ($isstaion) {
			$return = array();
			if ($p) {
				$return["price"] = $p["nation_price"];
			}
		} else {
			if ($p) {
				$subnationPrice = $do->getSubnationPrice();
			}

			$return          = array();
			$return["price"] = 0;
			foreach ($subnationPrice as $areaid => $price) {
				if (in_array($areaid, $cities) || in_array($AREA[$areaid]["parentid"], $cities)) {
					$return["price"] = $return["price"] + $price;
				}
			}
		}

		exit(json_encode($return));
		break;
	case  "charges":
		require_once './include/module.func.php';
		$userinfo = userinfo($username);
		$areas = $areas ? explode(',',$areas) : 0;
		$citylen = count($areas);
		if($areas==0){
			$citylen = $db->count($db->getPre().'city');
		}
		$total = push_charge($groupid,$userinfo,$areas,$moduleid);
		$return = array('success'=>$total['success'],'message'=>$total['total'],'citylen'=>$citylen);
		echo json_encode($return);
		break;
}